package main

import (
	"fmt"
	"time"
)

func main() {
	var fillInterval = time.Millisecond * 10
	var capacity = 100
	var tokenBucket = make(chan struct{}, capacity)
	fillToken := func() {
		ticker := time.NewTicker(fillInterval * 10)
		for {
			select {
			case <-ticker.C: // 定时器
				select {
				case tokenBucket <- struct{}{}:
					fmt.Printf("往令牌桶添加元素  令牌桶大小： %v \n", len(tokenBucket))
				default:
					// 令牌桶已满
				}
			}
		}
	}
	takeToken := func() {
		// 等待令牌桶预热
		time.Sleep(time.Millisecond * 5000)
		for {
			time.Sleep(time.Millisecond * 100)
			_, ok := <-tokenBucket
			if ok {
				fmt.Println("从令牌桶取出元素")
			} else {
				fmt.Println("通道已关闭")
			}
		}
	}
	go fillToken()
	go takeToken()
	time.Sleep(time.Hour)
}
